import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:get/get.dart';
import 'package:roswell_rgbw/commont/bg_page.dart';
import 'package:roswell_rgbw/const/const.dart';

import 'custom_picker_view.dart';
import 'home_controller.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final controller = Get.find<HomeController>();
  late final CircularColorPicker _coloCircular;
  @override
  void initState() {
    super.initState();

    ///色盘呢
    _coloCircular = CircularColorPicker(
      cirulaImage: assets.color,
      pointImage: assets.color_point,
      // padding: const EdgeInsets.only(left: 20, right: 20),
      onChange: (p0) => controller.updateCircleColor(p0),
    );
    controller.picker = _coloCircular;
    controller.listenBT(context);

    ///监听灯的类型
    GlobalDataNotifier().dataStream.listen((data) {});
  }

  Widget buildSlider(
    BuildContext context,
    String tag,
    List<Color> colors, {
    void Function(double)? onChanged,
    void Function(double)? onChangedForSend,
  }) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constranits) {
        final width = constranits.maxWidth;
        final height = constranits.maxHeight;
        return Container(
          color: Colors.transparent,
          width: width,
          height: height,
          child: Stack(
            children: [
              Positioned(
                left: 0,
                right: 0,
                bottom: 5,
                child:
                    // Text(
                    //   tag,
                    //   textAlign: TextAlign.center,
                    //   style: TextStyle(color: Colors.white, fontSize: 18),
                    // ),
                    Image.asset(tag == 'BRT' ? assets.light : assets.speed, width: 24, height: 24),
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 30,
                top: 0,
                child: Obx(() {
                  final model = tag == 'BRT' ? controller.brt.value : controller.spd.value;
                  return SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      trackHeight: 14,
                      trackShape: GradientSliderTrackShape(
                        gradient: LinearGradient(colors: colors, stops: [0.0, 0.5, 1.0]),
                      ),
                      thumbColor: Colors.white,
                      overlayColor: Colors.white.withOpacity(0.2),
                      thumbShape: RoundSliderThumbShape(enabledThumbRadius: 14),
                      overlayShape: const RoundSliderOverlayShape(overlayRadius: 0.0), // 设置圆点到两端的间距为 0 以减小间距
                    ),
                    child: kSlider(
                      milliseconds: 30,
                      dirction: Axis.horizontal,
                      value: model.value.toDouble(),
                      min: model.min.toDouble(),
                      max: model.max.toDouble(),
                      onChanged: onChanged,
                      onChangedForSend: onChangedForSend,
                    ),
                  );
                }),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    // 背景框框的高度
    final bg_line_h = 1002 / 1345 * (screenWidth - 68);
    return Scaffold(
      extendBody: true, // 让内容延伸到导航栏底部
      backgroundColor: Colors.transparent,
      appBar: null,
      body: SafeArea(
        child: BgPage(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            spacing: 0,
            children: [
              //
              SizedBox(height: 20),

              // logo
              SizedBox(
                height: 100,
                child: Image.asset(assets.LOGO, width: screenWidth * 0.7, fit: BoxFit.contain),
              ),
              // 分段选择
              // SizedBox(
              //   height: 30,
              //   width: screenWidth,
              //   child: Obx(() {
              //     return Center(
              //       child: ToggleButtons(
              //         borderRadius: BorderRadius.circular(8),
              //         borderColor: themeColor,
              //         borderWidth: 0.8,
              //         color: themeColor,
              //         selectedColor: Colors.white,
              //         selectedBorderColor: themeColor,
              //         isSelected: controller.types.map(($0) => $0 == controller.type.value).toList(),
              //         children: controller.types.asMap().entries.map(($0) {
              //           return Container(
              //             width: 80,
              //             color: $0.value == controller.type.value ? themeColor : Colors.black,
              //             child: Center(child: Text($0.value)),
              //           );
              //         }).toList(),
              //         onPressed: (index) => controller.changeType(index),
              //       ),
              //     );
              //   }),
              // ),

              ///中间圆盘设置
              Flexible(
                flex: 4,
                child: Container(
                  padding: EdgeInsets.all(10),
                  child: Stack(
                    children: [
                      /// 框框背景
                      Positioned(left: 0, bottom: 0, right: 0, child: Image.asset(assets.bg_setting)),

                      /// 圆盘
                      Positioned(
                        left: 30,
                        height: screenWidth - 80,
                        bottom: bg_line_h / 2,
                        right: 30,
                        child: LayoutBuilder(
                          builder: ((BuildContext context, BoxConstraints constraints) {
                            return Padding(
                              padding: EdgeInsets.all(25),
                              child: Obx(() {
                                return Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(
                                      min(constraints.maxWidth, constraints.maxHeight) / 2,
                                    ),
                                    border: BoxBorder.all(color: Color(controller.currentColor.decimal), width: 5),
                                  ),
                                  child: _coloCircular,
                                );
                              }),
                            );
                          }),
                        ),
                      ),
                      Positioned(
                        left: 0,
                        bottom: 0,
                        height: bg_line_h + 20,
                        width: 40,
                        child: buildSlider(
                          context,
                          'BRT',
                          [Colors.black, Colors.pink, Colors.white],
                          onChanged: (p0) => controller.updateBright(p0, false),
                          onChangedForSend: (p0) => controller.updateBright(p0, true),
                        ),
                      ),
                      Positioned(
                        right: 0,
                        bottom: 0,
                        height: bg_line_h + 20,
                        width: 40,
                        child: buildSlider(
                          context,
                          'SPD',
                          [Colors.black, themeColor, Colors.white],
                          onChanged: (p0) => controller.updateSpeed(p0, false),
                          onChangedForSend: (p0) => controller.updateSpeed(p0, true),
                        ),
                      ),

                      Align(
                        alignment: Alignment.bottomCenter,
                        child: Container(
                          margin: EdgeInsets.only(bottom: 5),
                          width: 60,
                          height: 20,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(3),
                            color: Colors.black,
                            border: BoxBorder.all(color: themeColor),
                          ),
                          child: Text('MODE', textAlign: TextAlign.center),
                        ),
                      ),

                      ///颜色模式
                      Positioned(
                        bottom: 35,
                        left: 60,
                        right: 60,
                        child: Center(
                          child: SizedBox(
                            width: 200,
                            height: 80,
                            child: Obx(() {
                              return CustomPickerview(
                                items: [controller.colorModeList.map(($0) => $0.keys.first).toList()],
                                selectIndexs: [controller.colorModeIndex.value],
                                onChanged: (p0, p1) => controller.updateColorMode(p1),
                              );
                            }),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              /// 红绿蓝颜色按钮选择
              Flexible(
                flex: 1,
                child: GridView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  padding: const EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 10),
                  itemCount: controller.colorItems.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: (controller.colorKeys.length / 2).toInt(),
                    childAspectRatio: 1,
                    mainAxisSpacing: 5,
                    crossAxisSpacing: 5,
                  ),
                  itemBuilder: (BuildContext context, index) {
                    return Obx(() {
                      bool isSelected = controller.colorIndex.value == index;
                      List<BoxShadow>? shadow = isSelected
                          ? [BoxShadow(color: Colors.transparent, blurRadius: 10, offset: Offset(0, 0))]
                          : null;
                      return Material(
                        color: Colors.transparent, // 保持原透明背景
                        borderRadius: BorderRadius.circular(8),
                        clipBehavior: Clip.antiAlias, // ✅ 关键：启用裁剪
                        child: InkWell(
                          focusColor: Colors.amber,
                          hoverColor: Colors.red,
                          splashColor: Colors.transparent,
                          highlightColor: themeColor,
                          onTap: () => controller.selectColorItem(index),
                          onLongPress: () => controller.deleteColorItem(index),
                          child: Transform.scale(
                            scale: isSelected ? 1 : 0.85, // 放大 10% 可自行调整
                            child: Container(
                              decoration: BoxDecoration(boxShadow: shadow),
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Color(controller.colorItems[index]),
                                  border: BoxBorder.all(color: themeColor, width: isSelected ? 4 : 0),
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Center(
                                  child: controller.colorKeys[index].isNotEmpty
                                      ? FittedBox(
                                          fit: BoxFit.scaleDown,
                                          child: Text(
                                            controller.colorKeys[index] == 'RGBW' ? 'RGBW' : '',
                                            style: TextStyle(color: Colors.black),
                                          ),
                                        )
                                      : Image.asset(assets.add2, width: screenWidth * 0.5),
                                ),
                              ),
                            ),
                          ),
                        ),
                      );
                    });
                  },
                ),
              ),

              // 底部按钮
              SizedBox(
                height: 100,
                child: Container(
                  color: Colors.transparent,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: List.generate(controller.tabIcons.length, ($0) {
                      return Obx(() {
                        return InkWell(
                          child: Image.asset(controller.tabIcons[$0], width: 50, height: 50),
                          onTap: () => controller.tapBottom(context, $0),
                        );
                      });
                    }).toList(),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
